package com.lagou.server.threadpool;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool;

import java.util.Map;
import java.util.concurrent.*;

/**
 * 自定义
 * @author 陶肖寅
 * @version V1.0
 * @Package com.lagou.threadpool
 * @email fromlx@126.com
 * @date 2020-04-16 20:31
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 */
public class MonitorThreadPool extends FixedThreadPool implements  Runnable{
    //定义线程阀值
    private static  final  double ALARM_PERCENT=0.9;
    private final Map<URL, ThreadPoolExecutor> THEAD_POOLS = new ConcurrentHashMap<>();
    public MonitorThreadPool(){
        //每隔5秒打印T99,T90情况
        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(this,1,5,TimeUnit.HOURS);
    }
    //通过父类创建线程池
    @Override
    public void run() {
        //遍历线程池
        for(Map.Entry<URL,ThreadPoolExecutor> entry:THEAD_POOLS.entrySet()){
            final URL url = entry.getKey();
            final  ThreadPoolExecutor executor = entry.getValue();
            //计算数据
            final  int activeCount = executor.getActiveCount();
            final  int poolSize = executor.getPoolSize();
            double userPercent = activeCount/(poolSize*1.0);
            System.out.println("线程池执行状态：["+activeCount+"/"+poolSize+":"+userPercent+"%]");
            if (userPercent > ALARM_PERCENT) {
                //超出警戒线
                System.out.println(url.getIp()+":"+userPercent);
            }

        }
    }

    @Override
    public Executor getExecutor(URL url) {
        final Executor executor = super.getExecutor(url);
        if(executor instanceof  ThreadPoolExecutor) {
            THEAD_POOLS.put(url,(ThreadPoolExecutor) executor);
        }
        return executor;
    }
}
